﻿CREATE PROCEDURE [dbo].[usp_select_BatchResubmissionMessagesToProcess]
	@Debug BIT = 0
AS

	DECLARE @vProcessingID UNIQUEIDENTIFIER = NEWID()

	IF @Debug = 1
	BEGIN
		print '[usp_select_BatchResubmissionMessagesToProcess]: @vCurrentTime = ' + CONVERT(varchar(50), GETDATE())
		print '[usp_select_BatchResubmissionMessagesToProcess]: @vProcessingID = ' + CONVERT(varchar(50), @vProcessingID) 
	END

	DECLARE @vBatchID UNIQUEIDENTIFIER

	BEGIN TRY

	EXEC sp_BuildBatchForResubmission @vBatchID output, @Debug

	END TRY
	BEGIN CATCH
		DECLARE @error int, @message varchar(4000), @xstate int;
		SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
       
		RAISERROR ('[usp_select_BatchResubmissionMessagesToProcess]: %d: %s', 16, 1, @error, @message) ;
		RETURN;
	END CATCH

	
	-- Get the batch messages that have been marked for resubmission.
	BEGIN TRY

		BEGIN TRANSACTION T1

			-- Get the number of messages to process at a time.
			DECLARE @BatchResubmitNumberOfMessages INT =
			(
				SELECT TOP 1 Value FROM Configuration WHERE Name = 'BatchResubmitNumberOfMessages'
			)

			-- Updated message id's will be output into this table to know which messages to return.
			DECLARE @BatchResubmissionMessageIDs TABLE (ID INT)

			UPDATE TOP (@BatchResubmitNumberOfMessages) brm SET ProcessingID = @vProcessingID
			OUTPUT inserted.ID INTO @BatchResubmissionMessageIDs
			FROM
				BatchResubmission br 
				JOIN BatchResubmissionMessage brm ON 
					br.BatchID = brm.MessageBatchID
					AND brm.[Status] = 'Processing'
					AND brm.ProcessingID IS NULL
			WHERE
				br.BatchID = @vBatchID

			SELECT 
				brm.ID AS BatchResubmissionID,
				br.ResubmissionURI,
				m.*,
				md.MessageData
			FROM 
				BatchResubmissionMessage brm
				JOIN @BatchResubmissionMessageIDs brmIDs ON brm.ID = brmIDs.ID
				JOIN BatchResubmission br ON brm.MessageBatchID = br.BatchID
				JOIN [Message] m ON brm.MessageID = m.MessageID
				JOIN MessageData md ON m.MessageID = md.MessageID

		COMMIT TRANSACTION T1
	END TRY
	BEGIN CATCH
		SELECT @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();

		ROLLBACK TRANSACTION T1
        
		RAISERROR ('[usp_select_BatchResubmissionMessagesToProcess]: %d: %s', 16, 1, @error, @message) ;
		RETURN;
	END CATCH


RETURN 0
